package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    //从服务端
    @Reference
    private MemberService memberService;


    @RequestMapping("/login")
    public Result login(@RequestBody Map map,HttpServletResponse response){
        //校验验证码是否正确
            //获取手机
        String telephone = (String) map.get("telephone");
            //获取验证码
        String validateCode = (String) map.get("validateCode");
        //从redis中取出登录验证码
        String redisValidateCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //判断
        if (validateCode != null && redisValidateCode != null && validateCode.equals(redisValidateCode)){
             //判断当前用户是否已经注册
            Member member = memberService.findByTelephone(telephone);
            if (member == null){ //不是会员
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //将登录信息添加到Cookies
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");
            response.addCookie(cookie);
            //将会员信息保存带redis中
                //将实体类转换成json  因为redis中无法存实体类
            String member_json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,member_json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }else{//验证码校验失败
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
